<template>
	<div class="addTask">
		<div class="addTask-head">
			<el-steps :active="active" finish-status="success" align-center>
				<el-step title="基本设置" />
				<el-step title="调度对象" />
				<el-step title="调度周期" />
				<el-step title="文件处理" />
			</el-steps>

			<div class="pre-next-button">
				<el-button v-if="active !== 0 && active !== 4" style="margin-top: 12px" type="primary" @click="pre">上一步</el-button>
				<el-button v-if="active < 3" style="margin-top: 12px" type="primary" @click="next">下一步</el-button>
				<el-button v-if="active == 3" style="margin-top: 12px" type="primary" @click="save">保存</el-button>
				<el-button v-if="active == 4" style="margin-top: 12px" type="primary" @click="back">返回</el-button>
			</div>
		</div>
		<div class="addTask-content">
			<div v-if="active === 0">
				<el-col :span="10">
					<el-form ref="baseSettings" :inline="true" :model="formData">
						<el-form-item
							prop="taskName"
							style="width: 100%"
							label="任务名称"
							:rules="{ required: true, message: '任务名称不能为空', trigger: 'blur' }"
						>
							<el-input v-model="formData.taskName" placeholder="请输入定时调度任务名称" clearable />
						</el-form-item>
					</el-form>
				</el-col>
			</div>
			<div v-if="active === 1">
				<el-col :span="12">
					<el-form ref="scheduleObj" :inline="true" :model="formData" :label-width="120">
						<el-form-item style="width: 100%" label="对象类型">
							<el-radio v-model="formData.objType" :label="0">报表模板</el-radio>
						</el-form-item>
						<el-form-item
							style="width: 100%"
							label="选择模版"
							prop="reportTemplateId"
							:rules="{ required: true, message: '请选择模板', trigger: 'blur' }"
						>
							<el-select v-model="formData.reportTemplateId" placeholder="报表名称-日期" filterable>
								<el-option
									v-for="item in templateOptions"
									:key="item.id"
									:label="item.name"
									:value="item.id"
									@click="changeTemplate(item.name)"
								></el-option>
							</el-select>
						</el-form-item>
						<el-form-item style="width: 83%" label="参数设置" prop="params" :rules="{ required: true, message: '参数设置不能为空', trigger: 'blur' }">
							<el-date-picker
								v-model="formData.params"
								type="datetimerange"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								value-format="YYYY-MM-DD HH:mm:ss"
								@change="onDateChange"
							/>
						</el-form-item>
						<el-form-item
							style="width: 83%"
							label="文件名称"
							prop="reportFileName"
							:rules="{ required: true, message: '文件名称不能为空', trigger: 'blur' }"
						>
							<el-input v-model="formData.reportFileName" placeholder="建议命名命名：${today()}的定时日报" clearable />
						</el-form-item>
						<el-form-item style="width: 100%" label="附件存档">
							<el-checkbox v-model="formData.reportFileFormat" true-label="excel" label="excel" checked />
						</el-form-item>
						<el-form-item style="width: 100%" label="文件处理">
							<el-radio-group v-model="formData.reportFileRetentionTime">
								<el-radio :label="1">仅保留最近1次</el-radio>
								<el-radio :label="7">仅保留最近7次</el-radio>
								<el-radio :label="-1">不清理</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-form>
				</el-col>
			</div>
			<div v-if="active === 2">
				<el-form :inline="true" :model="formData">
					<div>
						<el-form-item label="开始时间">
							<el-radio v-model="formData.taskStartType" :label="0"
								>设定开始时间
								<el-date-picker
									v-model="formData.taskStartTime"
									style="width: 70%"
									format="YYYY-MM-DD HH:mm:ss"
									value-format="YYYY-MM-DD HH:mm:ss"
									type="datetime"
									placeholder="请选择开始时间"
								/>
							</el-radio>
						</el-form-item>
					</div>
					<div>
						<el-form-item label="执行频率" style="width: 100%">
							<el-radio-group v-model="formData.taskExecuteFrequency" style="width: 50%" @change="changeFrequency">
								<el-radio :label="0">只执行一次</el-radio>
								<el-radio :label="1" :style="{ width: formData.taskExecuteFrequency === 1 ? '50%' : 'auto' }"
									>简单重复执行
									<span v-if="formData.taskExecuteFrequency === 1" style="vertical-align: middle; color: white"
										>每隔
										<el-input-number
											v-model="formData.num"
											:min="0"
											size="small"
											:precision="0"
											:controls="false"
											style="width: 64px; margin-right: 5px"
										></el-input-number>
										<el-select v-model="formData.min" style="width: 60px" size="small">
											<el-option v-for="item in timeTypes" :key="item.value" :label="item.label" :value="item.value"></el-option>
										</el-select>
										执行一次
									</span>
								</el-radio>
								<el-radio :label="2"
									>表达式设置项
									<el-select v-if="formData.taskExecuteFrequency === 2" v-model="formData.taskCronExpressionStr" placeholder="请选择执行频率">
										<el-option v-for="item in frequencies" :key="item.value" :label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</div>
					<div>
						<el-form-item label="结束时间" style="width: 100%">
							<el-radio-group v-model="formData.taskEndType" style="width: 50%" @change="changeEndType">
								<el-radio v-if="formData.taskExecuteFrequency === 0" :label="undefined">任务执行一次后即结束</el-radio>
								<el-radio v-if="formData.taskExecuteFrequency !== 0" :label="0">无限时间</el-radio>
								<el-radio v-if="formData.taskExecuteFrequency !== 0" :label="1" :style="{ width: formData.taskEndType === 1 ? '50%' : 'auto' }"
									>设定结束时间
									<el-date-picker
										v-if="formData.taskEndType === 1"
										v-model="formData.taskEndValue"
										style="width: 70%"
										value-format="YYYY-MM-DD HH:mm:ss"
										type="datetime"
										placeholder="请选择结束时间"
									/>
								</el-radio>
								<el-radio v-if="formData.taskExecuteFrequency === 1" :label="2"
									>额外重复执行次数
									<el-input-number
										v-if="formData.taskEndType === 2"
										v-model="formData.taskEndValue"
										placeholder="请输入正整数"
										:min="0"
										size="small"
										:precision="0"
										:controls="false"
										style="width: 105px; margin-right: 5px"
									></el-input-number>
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</div>
					<div>
						<el-form-item label="执行条件">
							<el-radio v-model="formData.condition" label="始终执行"></el-radio>
						</el-form-item>
					</div>
					<el-col :span="8">
						<el-form-item label="任务重启">
							<el-checkbox
								v-model="formData.taskRestartFlag"
								:checked="formData.taskRestartFlag === 1 ? true : false"
								label="如果任务中断按以下频率重新启动"
								:true-label="1"
								:false-label="0"
							></el-checkbox>
							<p v-if="formData.taskRestartFlag === 1" style="vertical-align: middle; color: white">
								两次重启间隔：
								<el-input-number
									v-model="formData.taskRestartInterval"
									:min="0"
									size="small"
									:precision="0"
									:controls="false"
									style="width: 64px; margin-right: 5px"
								></el-input-number>
								分钟
							</p>
							<p v-if="formData.taskRestartFlag === 1" style="vertical-align: middle; color: white">
								最多尝试重启次数：
								<el-input-number
									v-model="formData.taskRestartCount"
									:min="0"
									size="small"
									:precision="0"
									:controls="false"
									style="width: 64px; margin-right: 5px"
								></el-input-number>
								次
							</p>
						</el-form-item>
					</el-col>
				</el-form>
			</div>
			<div v-if="active === 3">
				<el-col :span="12">
					<el-form ref="process" :inline="true" :model="formData" :rules="rules" :label-width="100">
						<el-form-item style="width: 100%" label="处理方式">
							<el-checkbox-group v-model="formData.taskNotificationPolicyList">
								<el-checkbox label="0">邮件通知</el-checkbox>
								<el-checkbox label="1">第三方接口通知</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
						<el-row v-if="formData.taskNotificationPolicyList.includes('0')">
							<p class="method-label">邮件通知</p>
							<el-form-item style="width: 100%" label="发件人" prop="emailSender">
								<el-select v-model="formData.emailSender" placeholder="请选择发件人" filterable clearable>
									<el-option v-for="item in options" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item style="width: 100%" label="收件人" prop="emailRecipientList">
								<el-select v-model="formData.emailRecipientList" placeholder="请选择收件人" multiple filterable clearable>
									<el-option v-for="item in receiveOptions" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item style="width: 80%" label="自定义邮箱">
								<el-input v-model="formData.emailRecipientCustom" placeholder="自定义邮箱" clearable />
							</el-form-item>
							<el-form-item style="width: 100%" label="抄送">
								<el-select v-model="formData.emailCcByList" placeholder="请选择抄送人" filterable clearable multiple>
									<el-option v-for="item in receiveOptions" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item style="width: 80%" label="自定义邮箱">
								<el-input v-model="formData.emailCcByCustom" placeholder="自定义邮箱" clearable />
							</el-form-item>
							<el-form-item style="width: 100%" label="密送">
								<el-select v-model="formData.emailBccRecipientList" placeholder="请选择密送人" filterable clearable multiple>
									<el-option v-for="item in receiveOptions" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item style="width: 80%" label="自定义邮箱">
								<el-input v-model="formData.emailBccRecipientCustom" placeholder="自定义邮箱" clearable />
							</el-form-item>
							<el-form-item style="width: 80%" label="主题">
								<el-input v-model="formData.emailSubject" placeholder="建议主题：${today()}的定时日报" clearable />
							</el-form-item>
							<el-form-item style="width: 80%" label="邮件内容">
								<el-input v-model="formData.emailContent" type="textarea" :rows="4" resize="none" placeholder="请输入邮箱正文内容" clearable />
							</el-form-item>
							<el-form-item style="width: 100%" label="   ">
								<el-checkbox
									v-model="formData.emailBodyLinkFlag"
									:checked="formData.emailBodyLinkFlag === 0 ? false : true"
									:true-label="1"
									:false-label="0"
									>正文附报表预览链接</el-checkbox
								>
							</el-form-item>
							<el-form-item style="width: 100%" label="   ">
								<el-checkbox
									v-model="formData.emailAttachmentFlag"
									:checked="formData.emailAttachmentFlag === 1 ? true : false"
									:true-label="1"
									:false-label="0"
									>使用附件</el-checkbox
								>
							</el-form-item>
						</el-row>
						<el-row v-if="formData.taskNotificationPolicyList.includes('1')">
							<p class="method-label">第三方通知</p>
							<el-form-item style="width: 100%" label="收件人" prop="interfaceRecipienList">
								<el-select v-model="formData.interfaceRecipientList" placeholder="请选择收件人" filterable clearable multiple>
									<el-option v-for="item in receiveOptions" :key="item.id" :label="item.nickName" :value="item.id"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item style="width: 80%" label="通知内容">
								<el-input v-model="formData.interfaceContent" type="textarea" :autosize="false" placeholder="请输入消息正文内容" clearable />
							</el-form-item>
							<el-form-item style="width: 100%" label=" ">
								<el-checkbox
									v-model="formData.interfaceBodyLinkFlag"
									:checked="formData.interfaceBodyLinkFlag === 0 ? false : true"
									:true-label="1"
									:false-label="0"
									>正文附报表预览链接</el-checkbox
								>
							</el-form-item>
						</el-row>
					</el-form>
				</el-col>
			</div>
			<div v-if="active === 4" class="add-success">
				<div>
					<p v-if="props.taskId">更新任务成功，请返回任务管理</p>
					<p v-else>添加任务成功，请返回任务管理</p>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="tsx" name="AddTask" setup>
import { ref, reactive, toRefs, onMounted, onActivated, getCurrentInstance, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { parseTime } from '@/utils/common';
import { saveTaskInfo, excelQuery, getTaskInfoById, getCronList, updateTaskInfo } from '@/api/ops-workbench/timeSchedule/taskManagement';
import { getPushObjectUserList, getPushObjectEmailAdressList } from '@/api/ops-workbench/timeSchedule/globalSetting';
const { proxy }: any = getCurrentInstance();

const router = useRouter();
const route = useRoute();
const emit = defineEmits(['changeActive', 'changeComponent']);
const props = defineProps({
	taskId: {
		type: Boolean,
		required: true,
	},
});

getTemplates();
getFrequencies();
const active = ref(0);
let templateOptions = reactive<anyObj>({});
// 发件人选项
const options = ref<anyObj>([]);
// 收件人、密送、抄送选项
const receiveOptions = ref<anyObj>([]);
// 执行频率 表达式设置项
let frequencies = reactive<anyObj>({});

// 执行频率 时间类型
const timeTypes = ref([
	{ label: '分钟', value: 'MIN' },
	{ label: '小时', value: 'HOUR' },
	{ label: '天', value: 'DAY' },
	{ label: '周', value: 'WEEK' },
]);

// 表单校验
const rules = ref<anyObj>({
	emailSender: [{ required: true, message: '发件人不能为空', trigger: 'blur' }],
	emailRecipientList: [{ required: true, message: '收件人不能为空', trigger: 'blur' }],
	interfaceRecipientList: [{ required: true, message: '收件人不能为空', trigger: 'blur' }],
});

let formData = ref<FormModelType>({
	objType: 0,
	condition: '始终执行',
	taskRestartFlag: 0,
	taskNotificationPolicyList: [],
	taskStartTime: parseTime(new Date().getTime()),
	taskStartType: 0,
	taskEndType: undefined,
	taskExecuteFrequency: 0,
	reportFileRetentionTime: -1,
});

onMounted(() => {
	getTaskInfoDetail();
});

function onDateChange(val: any) {
	formData.value.reportQueryStartTime = val[0];
	formData.value.reportQueryEndTime = val[1];
}
const next = () => {
	console.log(active.value);
	if (active.value === 0) {
		proxy.$refs['baseSettings'].validate((valid: anyObj) => {
			if (valid) {
				active.value++;
				if (formData.value.reportTemplateId && Object.keys(templateOptions).length !== 0) {
					const selectedOption = templateOptions.find((option: anyObj) => option.id === formData.value.reportTemplateId);
					formData.value.reportTemplateName = selectedOption.name;
				}
			}
		});
	} else if (active.value === 1) {
		proxy.$refs['scheduleObj'].validate((valid: anyObj) => {
			if (valid) {
				active.value++;
			}
		});
	} else if (active.value === 2) {
		if (formData.value.taskExecuteFrequency === 1) {
			formData.value.taskCronExpressionStr = formData.value.num + '_' + formData.value.min;
			console.log(formData.value.taskCronExpressionStr, 'formData.taskCronExpressionStr');
		}
		active.value++;
	} else {
		active.value++;
	}
	if (active.value > 4) active.value = 0;
	emit('changeActive', active.value);
};
const pre = () => {
	active.value--;
	emit('changeActive', active.value);
};

const back = () => {
	emit('changeComponent', 1);
	formData.value = {};
};
function changeEndType(val: number | string) {
	console.log(val);
	if (val === 1) {
		formData.value.taskEndValue = parseTime(new Date(formData.value.taskStartTime).getTime() + 60 * 60 * 1000);
	} else if (val === 2) {
		formData.value.taskEndValue = 1;
	}
}
// 获取任务信息详情
function getTaskInfoDetail() {
	console.log(props.taskId, 'TASKiD');
	if (props.taskId) {
		getTaskInfoById(props.taskId).then((res: ApiResponse) => {
			console.log('formData', formData);
			formData.value = res.data;
			formData.value.objType = 0;
			formData.value.condition = '始终执行';
			formData.value.taskStartType = 0;
			if (!formData.value.taskNotificationPolicyList) {
				formData.value.taskNotificationPolicyList = [];
			}
			if (formData.value.taskCronExpressionStr && formData.value.taskCronExpressionStr.includes('_')) {
				let params = formData.value.taskCronExpressionStr.split('_');
				console.log(params, 'pp');
				formData.value.num = params[0];
				formData.value.min = params[1];
			}
			if (formData.value.reportQueryStartTime && formData.value.reportQueryEndTime) {
				formData.value.params = [formData.value.reportQueryStartTime, formData.value.reportQueryEndTime];
				console.log('没有参数设置吗？');
			}
			if (formData.value.taskExecuteFrequency === 0) {
				formData.value.taskEndType = undefined;
			}
		});
	}
}
// 保存
const save = () => {
	if (active.value === 3) {
		proxy.$refs['process'].validate((valid: anyObj) => {
			if (valid) {
				console.log(props.taskId);
				if (props.taskId) {
					updateTaskInfo(formData.value)
						.then((res: ApiResponse) => {
							if (res.code === 0) {
								active.value++;
								emit('changeActive', active.value);
							} else {
								proxy.$modal.msgError(res.msg);
							}
						})
						.catch((e) => {
							proxy.$modal.msgError(e);
						});
				} else {
					saveTaskInfo(formData.value)
						.then((res: ApiResponse) => {
							if (res.code === 0) {
								active.value++;
								emit('changeActive', active.value);
							} else {
								proxy.$modal.msgError(res.msg);
							}
						})
						.catch((e) => {
							proxy.$modal.msgError(e);
						});
				}
			}
		});
	}
};

function changeFrequency(val: number | string | boolean) {
	console.log(val, formData.value.taskCronExpressionStr);

	if (val === 0) {
		formData.value.taskEndType = undefined;
	} else {
		formData.value.taskEndType = 0;
	}
	if (val === 2) {
		formData.value.taskCronExpressionStr = frequencies[0].value;
	}
	if (val === 1) {
		formData.value.min = timeTypes.value[0].value;
		formData.value.num = 1;
	}
	// formData.value.taskCronExpressionStr = '';
}

function changeNotice(val: any) {
	// if (!formData.value.taskNotificationPolicyList.includes(0)) {
	// 	formData.value.emailSender = null;
	// 	formData.value.emailRecipientList = [];
	// 	formData.value.emailRecipientCustom = null;
	// 	formData.value.emailCcByList = [];
	// 	formData.value.emailCcByCustom = null;
	// 	formData.value.emailBccRecipientList = [];
	// 	formData.value.emailBccRecipientCustom = null;
	// 	formData.value.emailSubject = null;
	// 	formData.value.emailContent = null;
	// 	formData.value.emailBodyLinkFlag = 1;
	// 	formData.value.emailAttachmentFlag = 0;
	// }
	// if (!formData.value.taskNotificationPolicyList.includes(1)) {
	// 	formData.value.interfaceBodyLinkFlag = null;
	// 	formData.value.interfaceContent = null;
	// 	// formData.interfaceRecipientList = [];
	// }
}
// 获取模板
function getTemplates() {
	excelQuery().then((res) => {
		templateOptions = res.data;
	});
}
// 选择模板
function changeTemplate(val: string) {
	formData.value.reportTemplateName = val;
}
// 获取执行频率-表达式设置
function getFrequencies() {
	getCronList().then((res) => {
		frequencies = res.data;
	});
}
// 获取收件人、发件人、抄送人、密送人列表
getMailer();
function getMailer() {
	let params = { pageSize: -1, pageNum: -1 };
	getPushObjectEmailAdressList(params).then((res: ApiResponse) => {
		if (res.code === 0) {
			options.value = res.data.records;
		} else {
			proxy.$model.msgError(res.msg);
		}
	});
	getPushObjectUserList(params).then((res: ApiResponse) => {
		if (res.code === 0) {
			res.data.records.forEach((item: any) => {
				if (item.enable === null) {
					item.enable = 1;
				}
			});
			receiveOptions.value = res.data.records;
		} else {
			proxy?.$message(res.msg);
		}
	});
}
// 导出方法给父组件使用
defineExpose({ save });
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
body[data-theme='theme-dark'] {
	.el-input {
		width: 100%;
	}
}
:deep(.el-step__title.is-process),
:deep(.el-step__head.is-process) {
	color: var(--el-color-primary-darker);
	border-color: var(--el-color-primary-darker);
}
:deep(.el-step__head.is-success),
:deep(.el-step__title.is-success) {
	color: var(--el-color-primary);
	border-color: var(--el-color-primary);
}
.addTask {
	.addTask-head {
		padding: 10px 0;
		.pre-next-button {
			display: flex;
			justify-content: center;
			padding: 20px 0;
		}
	}
	.addTask-content {
		font-size: 16px;
		:deep(.el-form-item__label) {
			font-size: 20px;
			line-height: 40px;
			height: 40px;
			font-weight: bold;
			margin-right: 15px;
		}
		:deep(.el-row .el-form-item__label) {
			font-size: 14px;
		}
		:deep(.el-select) {
			width: 80%;
		}
		position: relative;
		.method-label {
			font-size: 20px;
			position: absolute;
			right: 0;
			color: var(--el-color-primary);
			font-weight: bold;
			margin-top: 5px;
		}
		.add-success {
			display: flex;
			justify-content: center;
		}
	}
}
</style>
<style lang="scss">
.addTask {
	:deep(.el-input) {
		width: 100% !important;
	}
}
</style>
